package com.yuanian.timingwheel.annotation.aspect;

import com.yuanian.timingwheel.annotation.TimingTask;
import com.yuanian.timingwheel.annotation.TimingTaskAnnoHandler;
import com.yuanian.timingwheel.annotation.TimingTaskType;
import com.yuanian.timingwheel.threadlocal.ThreadLocalEntity;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;

/**
 * 手工任务执行拦截器
 */
@Component
@Aspect
public class TimingTaskAspect extends TimingTaskAnnoHandler {

    @Around("@annotation(com.yuanian.timingwheel.annotation.TimingTask)")
    public Object timingTask(ProceedingJoinPoint joinPoint) throws Throwable {
        //任务被定时器调用
        if (ThreadLocalEntity.get() != null) {
            Object result = joinPoint.proceed();
            return result;
        }
        Method method = ((MethodSignature)joinPoint.getSignature()).getMethod();
        TimingTask timingTask = method.getAnnotation(TimingTask.class);
        if (timingTask.timingTaskType() == TimingTaskType.MANUAL) {//手工
            Object[] args = joinPoint.getArgs();
            Object target = joinPoint.getTarget();
            Class clz = target.getClass();
            //获取动态参数解析器
            String dynamicParamSolver = timingTask.dynamicParamSolver();
            handle(dynamicParamSolver, clz, method, target, args);
            return null;
        } else {
            Object result = joinPoint.proceed();
            return result;
        }
    }

}
